<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('searchText',text)"
    >
      <template #title>
        <div v-html="highLight(text)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { searchSuggestion } from '@/api/search.js'
import { debounce } from 'lodash'
export default {
  name: 'resultIndex',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      suggestions: []
    }
  },
  watch: {
    searchText: {
      immediate: true,
      handler: debounce(function (newVal) {
        this.searchSuggestionFn(newVal)
      }, 500)
    }
  },
  methods: {
    async searchSuggestionFn (q) {
      try {
        const res = await searchSuggestion(q)
        console.log(res.data)
        // null
        if (res.data.data.options[0] === null) {
          this.suggestions = []
        } else {
          this.suggestions = res?.data?.data?.options
        }
      } catch (err) {
        this.$toast('联想建议')
      }
    },
    highLight (text) {
      const htmlStr = `<span style="color: #3296fa;">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, htmlStr)
    }
  }
}
</script>

<style scoped lang='less'>
/deep/ .active {
  color: #3296fa;
}
</style>
